import 'dart:convert';

import 'package:eplorex/models/moment/comment_model.dart';
import 'package:eplorex/pages/community/moment/reply_area_widget.dart';
import 'package:flutter/material.dart';

import '../../../dao/momentinfo_dao.dart';

typedef ShowCommentInput<T> = void Function(num parentId, num replayId);

class CommentAreaWidget extends StatefulWidget {
  const CommentAreaWidget(
      {super.key,
      required this.commentsCnt,
      required this.momentId,
      required this.commentInput});

  final num commentsCnt;
  final ShowCommentInput commentInput;
  final int? momentId;

  @override
  State<CommentAreaWidget> createState() => _CommentAreaWidgetState();
}

class _CommentAreaWidgetState extends State<CommentAreaWidget> {
  late Future<List<CommentModel>?> _listComments;
  List<CommentModel>? _cachedComments;

  @override
  void initState() {
    _listComments = MomentInfoDao.fetchComment(widget.momentId);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      margin: EdgeInsets.only(left: 5, top: 10, right: 5),
      padding: EdgeInsets.symmetric(vertical: 8, horizontal: 8),
      child: Column(
        children: [
          Container(
            margin: EdgeInsets.only(bottom: 5),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '评论 ${widget.commentsCnt ?? "0"}',
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
                ),
                PopupMenuButton(
                  color: Colors.white,
                  offset: const Offset(0, 20),
                  itemBuilder: (BuildContext context) {
                    return <PopupMenuEntry<String>>[
                      PopupMenuItem(
                          child: Container(
                        child: Text("默认"),
                      )),
                      PopupMenuItem(child: Container(child: Text('时间'))),
                    ];
                  },
                  child: Container(
                      child: Row(
                    children: [
                      Text("默认"),
                      Icon(
                        Icons.filter_alt_outlined,
                        size: 20,
                        color: Colors.blue,
                      )
                    ],
                  )),
                ),
              ],
            ),
          ),
          Divider(
            height: 3,
            thickness: 0.3,
          ),
          Container(
            child: FutureBuilder(
              future: _listComments,
              builder: (BuildContext context,
                  AsyncSnapshot<List<CommentModel>?> snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Text("loading....");
                }
                _cachedComments= _cachedComments ??  snapshot.data;
                return Column(
                  children:
                  _cachedComments?.map((e) => buildComment(e)).toList() ??
                          [Text("快占沙发")],
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget buildComment(CommentModel commentModel) {
    return Container(
      margin: EdgeInsets.only(top: 10, bottom: 5),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            flex: 2,
            child: CircleAvatar(
              radius: 15,
              backgroundImage: NetworkImage(commentModel.userBaseInfo!.avatar!),
            ),
          ),
          Expanded(
            flex: 10,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  // color:colors.red,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Text(
                        commentModel.userBaseInfo!.userName!,
                        style: TextStyle(color: Colors.red),
                      )
                    ],
                  ),
                ),
                Text(commentModel.comment ?? " ",
                    style: const TextStyle(fontSize: 16)),
                SizedBox(
                  // width: 100,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Container(
                        child: Text(
                          '${commentModel.dateTime}  ${commentModel.userPosition ?? "未知位置"}',
                          style: TextStyle(fontSize: 12, color: Colors.grey),
                        ),
                      ),
                      Container(
                        child: Wrap(
                          children: [
                            GestureDetector(
                              onTap: () {
                                widget.commentInput(commentModel.commentId!,
                                    commentModel.commentId!);
                              },
                              child: const Padding(
                                padding: EdgeInsets.only(right: 10),
                                child: Icon(
                                  Icons.comment_outlined,
                                  size: 18,
                                  color: Colors.grey,
                                ),
                              ),
                            ),
                            GestureDetector(
                              onTap: () {},
                              child: Icon(
                                Icons.favorite_outline,
                                size: 18,
                                color: Colors.grey,
                              ),
                            )
                          ],
                        ),
                      )
                    ],
                  ),
                ),
                if (commentModel.replies != null &&
                    !commentModel.replies!.isEmpty)
                  Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(3),
                        color: Color.fromRGBO(220, 220, 220, 0.2)),
                    width: MediaQuery.of(context).size.width - 60,
                    child: Column(
                      children: buildReplies(
                              commentModel.replies, commentModel.commentId!) ??
                          [],
                    ),
                  ),
              ],
            ),
          )
        ],
      ),
    );
  }

  List<Widget>? buildReplies(List<Replies>? replies, num parentId) {
    return replies
        ?.map((e) => ReplyAreaWidget(
              replies: e,
              momentId: widget.momentId!,
              parentId: parentId.toInt(),
              commentInput: widget.commentInput,
            ))
        .toList();
  }
}
